package swordoffer.offer52;

public class RemoveLengthSolution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        //获取两个链表的长度
        int len1 = getLength(pHead1);
        int len2 = getLength(pHead2);
        //如果长度不相等，消除长度差
        while(len1 != len2){
            if(len1 > len2){
                pHead1 = pHead1.next;
                len1--;
            }else{
                pHead2 = pHead2.next;
                len2--;
            }
        }
        //此时两个链表不存在长度差，两个节点相遇即为第一个相交节点，如果链表不相交则返回null
        while(pHead1 != pHead2){
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return pHead1;
    }
    public int getLength(ListNode head){
        int length = 0;
        while(head != null){
            length++;
            head = head.next;
        }
        return length;
    }
}
